<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
                <el-form-item label="">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          label="#"
          align="center"
          width="80px;"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getPrepaymentList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="45%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        size="small"
        style="padding: 0 30px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="收款单号" prop="code">
              <el-input
                type="text"
                v-model="form.code"
                placeholder="收款单号"
                maxlength="24"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款时间" prop="order_time">
              <el-date-picker
                v-model="form.order_time"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="付款客户" prop="customer">
              <el-select
                v-model="form.customer"
                placeholder="付款客户"
                clearable
                filterable
              >
                <el-option
                  v-for="item in customers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账号" prop="account">
              <el-select
                v-model="form.account"
                placeholder="收款账号"
                clearable
              >
                <el-option
                  v-for="item in accounts"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收款金额" prop="amount">
              <el-input v-model="form.amount" placeholder="收款金额" clearable>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款人" prop="user">
              <el-select v-model="form.user" placeholder="收款人" clearable>
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.real_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="备注" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="HandleSave(false)"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getParentsPath } from "@/utils/index";
import { getCurrentDateTime } from "@/utils/datetime";
import {
  getPrepaymentMaxCode,
  getPrepayments,
  addPrepayment,
  updatePrepayment,
  delPrepayment,
  delPrepayments,
} from "@/api/finance";

import { getCustomerList } from "@/api/base";
import { getUserList } from "@/api/user";
import { getAccountList } from "@/api/finance";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  code: "",
  order_time: getCurrentDateTime(),
  customer: null,
  user: null,
  amount: null,
  deduct_amount: null,
  flag: 0,
  account: null,
  remark: "",
  oper_user: null,
};

export default {
  name: "Prepayment",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (!value || value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value < 0) {
          callback(new Error("不能小于零"));
        } else {
          callback();
        }
      }
    };

    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        code: [{ required: true, message: "请收款单号", trigger: "blur" }],
        customer: [
          { required: true, message: "请选择付款客户", trigger: "blur" },
        ],
        order_time: [
          { required: true, message: "请输入时间", trigger: "blur" },
        ],
        account: [{ required: true, message: "请选择账号", trigger: "blur" }],
        amount: [{ required: true, validator: checkMoney, trigger: "blur" }],
      },

      title: "预收款",
      datas: [],
      users: [],
      customers: [],
      accounts: [],
      selections: [],
      dialogVisible: false,

      dialogType: "new",
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: null,
        search_date: "",
      },

      tableColumns: [
        {
          key: "code",
          title: "收入单编号",
          width: "180",
        },
        {
          key: "order_time",
          title: "收款时间",
          width: "180",
        },
        {
          key: "customer_name",
          title: "付款客户",
        },
        {
          key: "user_name",
          title: "收款人",
        },

        {
          key: "amount",
          title: "收款金额",
        },
        {
          key: "deduct_amount",
          title: "已抵扣额",
        },
        {
          key: "account_name",
          title: "收入账号",
        },
        {
          key: "remark",
          title: "备注",
        },
        {
          key: "oper_user_name",
          title: "操作人",
        },
      ],

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getPrepaymentList();
    this.getUserCodeList();
    this.getAccountCodeList();
    this.getCustomers();
  },
  methods: {
    getPrepaymentList() {
      this.listLoading = true;
      getPrepayments(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.datas = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },

    getUserCodeList() {
      getUserList().then((res) => {
        this.users = res;
      });
    },

    getAccountCodeList() {
      getAccountList().then((res) => {
        this.accounts = res;
      });
    },

    getCustomers() {
      getCustomerList().then((res) => {
        this.customers = res;
      });
    },

    getPrepaymentMaxCode() {
      const params = {
        flag: this.form.flag,
      };
      getPrepaymentMaxCode(params).then((res) => {
        this.form.code = res.max_code;
      });
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "amount" ||
          column.property === "deduct_amount"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
      console.log(this.selections)
    },

        //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delPrepayments(sel_ids);

          this.getPrepaymentList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },


    dataFormatter(row, column, cellValue, index) {
      if (column.property == "amount" || column.property == "deduct_amount") {
        return cellValue && cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getPrepaymentList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.getPrepaymentMaxCode();
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delPrepayment(row.id);
          this.getPrepaymentList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async HandleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;

        if (isEdit) {
          if (!this.form.oper_user) {
            this.form.oper_user = this.uid;
          }
          res = await updatePrepayment(this.form);
        } else {
          this.form.oper_user = this.uid;
          try {
            res = await addPrepayment(this.form);
          } catch (err) {
            console.log(err);
            this.$message.error("保存失败!");
          }
        }

        this.getPrepaymentList();

        const { code, customer_name, amount } = res;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>单号: ${code}</div>
              <div>客户: ${customer_name}</div>
              <div>金额: ${amount}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }

  .item {
    margin-top: 8px;
  }
}
</style>